package www.dianbaozu.com.ui.chat.friendRequest

import android.provider.Contacts
import android.view.View
import androidx.fragment.app.viewModels
import com.luck.picture.lib.decoration.WrapContentLinearLayoutManager
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nimlib.sdk.RequestCallbackWrapper
import com.netease.nimlib.sdk.ResponseCode
import com.netease.nimlib.sdk.msg.model.SystemMessage
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.FlowPreview
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentFriendRequestBinding
import www.dianbaozu.com.ui.chat.friendRequest.adapter.FriendRequestAdapter
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.UnreadEntity
import www.wen.com.common.lib.extension.postObject
import www.wen.com.common.lib.extension.toast
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import android.provider.Contacts.People
import java.util.*
import kotlin.Comparator
import com.netease.nimlib.sdk.msg.constant.MsgStatusEnum

import com.netease.nimlib.sdk.msg.model.CustomMessageConfig

import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum

import com.netease.nimlib.sdk.msg.MessageBuilder

import com.netease.nimlib.sdk.msg.model.IMMessage





/**
 * @author WEN
 * @Description:好友请求
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class FriendRequestFragment : BaseLoadingFragment<FragmentFriendRequestBinding>() {

    private val friendRequestViewModel: FriendRequestViewModel by viewModels()

    private var offset = 0

    private val adapter: FriendRequestAdapter by lazy {
        FriendRequestAdapter(
            dataBinding.rvFriendRequest,
            R.layout.item_friend_request,
            mutableListOf(),
            object : FriendRequestAdapter.OnItemClick {
                override fun onAccept(position: Int, item: SystemMessage) {
                    if (position >= 0) {
                        NIMHelper.addFriendRequest(
                            item.fromAccount, true, object : RequestCallbackWrapper<Void?>() {
                                override fun onResult(
                                    code: Int,
                                    result: Void?,
                                    exception: Throwable?
                                ) {
                                    if (code != ResponseCode.RES_SUCCESS.toInt()) {
                                        toast(getString(R.string.add_failed))
                                        return
                                    }
                                    toast(getString(R.string.add_success))
                                    NIMHelper.deleteSystemMessage(item.messageId)
                                    adapter.data.removeAt(position)
                                    adapter.notifyItemRemoved(position)
                                    if (adapter.data.isEmpty()) {
                                        dataBinding.tvEmpty.visibility = View.VISIBLE
                                    }
                                    insertTip(item.fromAccount)
                                }
                            }
                        )
                    }
                }

                override fun onRefuse(position: Int, item: SystemMessage) {
                    if (position >= 0) {
                        NIMHelper.addFriendRequest(item.fromAccount, false, object :
                            RequestCallbackWrapper<Void>() {
                            override fun onResult(code: Int, result: Void?, exception: Throwable?) {
                                if (code != ResponseCode.RES_SUCCESS.toInt() && code != ResponseCode.RES_INVALID.toInt()) {
                                    toast(getString(R.string.refuse_failed))
                                    return
                                }
                                NIMHelper.deleteSystemMessage(item.messageId)
                                adapter.data.removeAt(position)
                                adapter.notifyItemRemoved(position)
                                if (adapter.data.isEmpty()) {
                                    dataBinding.tvEmpty.visibility = View.VISIBLE
                                }
                            }
                        })
                    }
                }
            })
    }

    override val viewModel: BaseViewModel
        get() = friendRequestViewModel

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
        TitleBarUniversalAdapter(requireActivity(), "好友请求", action = ::titleAction)

    override fun getLayoutId(): Int = R.layout.fragment_friend_request

    override fun lazyInitView() {
        NIMHelper.resetSystemMessageUnreadCount()
        dataBinding.apply {
            adapter.setOnLoadMoreListener {
                getAddFriendMsg()
            }
            adapter.setEnableLoadMore(true)
            rvFriendRequest.adapter = adapter
            rvFriendRequest.layoutManager = WrapContentLinearLayoutManager(requireActivity())
        }
        getAddFriendMsg()
    }

    @FlowPreview
    private fun getAddFriendMsg() {
        friendRequestViewModel.getAddFriendMsg(
            offset = offset,
            limit = 20,
            success = {
                offset += it.data.size
                if (it.data.isEmpty()) {
                    adapter.loadMoreEnd()
                } else {
                    val messages = TreeSet<SystemMessage> { o1, o2 ->
                        o1.fromAccount.compareTo(o2.fromAccount)
                    }
                    messages.addAll(adapter.data)
                    messages.addAll(it.data.filter { message -> !NIMHelper.isMyFriend(message.fromAccount) })
                    if (offset == 0) {
                        adapter.setNewData(messages.toList())
                        adapter.loadMoreComplete()
                    } else {
                        adapter.addData(messages.toList())
                        adapter.loadMoreComplete()
                    }
                    if (messages.isNotEmpty()) {
                        dataBinding.tvEmpty.visibility = View.GONE
                    }
                }
            },
            error = {
                adapter.loadMoreFail()
                if (adapter.data.isEmpty()) {
                    dataBinding.tvEmpty.visibility = View.VISIBLE
                }
            }
        )
    }

    fun insertTip(sessionId:String){
        // 创建tip消息
        val msg = MessageBuilder.createTipMessage(sessionId, SessionTypeEnum.P2P)
        msg.content = "你们已成为好友，可以开始聊天了"
        val content: MutableMap<String, Any> = HashMap(1)
        content["content"] = "你们已成为好友，可以开始聊天了"
        msg.remoteExtension = content
        // 自定义消息配置选项
        val config = CustomMessageConfig()
        // 消息不计入未读
        config.enableUnreadCount = false
        msg.config = config
        // 消息发送状态设置为success
        msg.status = MsgStatusEnum.success
        NIMHelper.sendMessage(msg)
    }

}



